import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:flutterlib/common/utils/sp_utils.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/message_event_entity.dart';
import 'package:thrio/thrio.dart';

class MessageChannelUtil {
  MessageChannelUtil._();

  static final _instance = MessageChannelUtil._();

  factory MessageChannelUtil() {
    return _instance;
  }

  static const _basicMessageChannel =
      const BasicMessageChannel('basic_channel', StringCodec());

  // receive
  void init() {
    trueDebugPrint("flutterchannel" +  "init handlebasicmessagej");
    _basicMessageChannel
        .setMessageHandler((String message) => Future<String>(() {
              trueDebugPrint("flutterchannel handlebasicmessagej" + message);
              var messageEventEntity =
                  MessageEventEntity.fromJson(json.decode(message));
              switch (messageEventEntity.type) {
                case "SETSP":
                  SpUtils().init().then((sp){
                    trueDebugPrint("flutterchannel sp put" + message);
                    SpUtils.putString(
                        messageEventEntity.key, messageEventEntity.value);
                  });
                  break;
                default:
              }
              return "success";
            }));
  }

  //send
  send(String type) async {
    String response = await _basicMessageChannel.send(type);
    return response;
  }
}
